package cn.me.alphamq.nameserver.event.spi.listener.cluster.slave;

import cn.me.alphamq.common.enumeration.EventCodeEnum;
import cn.me.alphamq.common.msg.TcpMsg;
import cn.me.alphamq.nameserver.cache.Container;
import cn.me.alphamq.nameserver.enumeration.ReplicationMsgCodeEnum;
import cn.me.alphamq.nameserver.event.model.cluster.ReplicationAckEvent;
import cn.me.alphamq.nameserver.event.model.cluster.ReplicationMsgEvent;
import cn.me.alphamq.common.event.Listener;
import cn.me.alphamq.nameserver.handler.cluster.masterslave.SlaveReplicationHandler;
import cn.me.alphamq.nameserver.store.ServiceInstance;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 主从同步中从节点的监听器，监听主节点发送的复制事件
 *
 * @author f
 */
public class SlaveReplicationMsgListener implements Listener<ReplicationMsgEvent> {

    private static final Logger log = LoggerFactory.getLogger(SlaveReplicationHandler.class);

    @Override
    public void onReceive(ReplicationMsgEvent event) throws Exception {
        // 从节点接收主节点同步的数据，并进行对应的修改
        ReplicationMsgCodeEnum msgCodeEnum = ReplicationMsgCodeEnum.of(event.getMsgCode());
        if (ReplicationMsgCodeEnum.INSERT_OR_UPDATE == msgCodeEnum) {
            // 如果是 添加/更新 数据，则使用 put()
            ServiceInstance serviceInstance = event.getServiceInstance();
            // 将主 nameserver 节点与其它服务实例的 channel 的上下文设置为 null
            serviceInstance.setCtx(null);
            Container.getServiceInstanceManager().put(serviceInstance);
        } else if (ReplicationMsgCodeEnum.DELETE == msgCodeEnum) {
            // 如果是 删除 数据，则使用 remove()
            Container.getServiceInstanceManager().remove(event.getKey());
        }

        // 给主节点回复 ack 消息表示完成复制
        event.getCtx().writeAndFlush(new TcpMsg(EventCodeEnum.SLAVE_REPLICATION_ACK_REQ,
                JSON.toJSONBytes(new ReplicationAckEvent(event.getMsgId()))));
//        log.info("从节点更新数据成功"); // TODO DELETE
    }
}
